package com.zkh.myutils.bean;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.zkh.myutils.io.log.Logger;
import com.zkh.myutils.utils.StringUtils;
import com.zkh.myutils.utils.UtilsException;

/**
 * Bean基础类型转换器
 * @author zkh
 */
public class BeanBaseTypeConverter {
	/**
	 * 基础类型
	 */
	static List<String> baseType = new ArrayList<String>(Arrays.asList(
		"byte", "short", "int", "long", "float", "double", "char", "boolean"
	));
	/**
	 * 不用解析的基础类型
	 */
	public static List<String> notParseType = new ArrayList<String>(Arrays.asList(
		"byte", "short", "int", "long", "float", "double", "char", "boolean",
		"Byte", "Short", "Integer", "Long", "Float", "Double", "Character", "Boolean",
		"BigDecimal", "BigInteger"
	));
	
	/**
	 * 转换为基础类型包装类
	 * @param typename 类型名称
	 * @param val 值
	 * @return
	 */
	public static Object toBaseType(String typename, Object val) {
		try {
			if(val==null) {
				return null;
			}
			//特殊类型
			if(StringUtils.isExist(typename, "BigDecimal", "BigInteger")) {
				String v = val.toString();
				//空字符串也返回空，避免前端单独处理太麻烦
				if(v.isEmpty()) {
					return null;
				}
				return Class.forName("java.math." + typename).getConstructor(String.class).newInstance(v);
			}
			//字符类型
			if(StringUtils.isExist(typename, "Character", "char")) {
				//转字符串
				String t = val.toString();
				//为空，默认空字符
				if(t==null) {
					return ' ';
				}else {
					return t.charAt(0);
				}
			}
			//检查格式
			typename = "int".equals(typename) ? "Integer" : StringUtils.uppercaseFirst(typename);
			//包装类，且为空字符串
			if(notParseType.indexOf(typename)>=8 && val.toString().isEmpty()) {
				return null;
			}
			//获取值
			return Class.forName("java.lang."+typename).getMethod("valueOf", String.class).invoke(null, val.toString());
		} catch (InvocationTargetException e) {
			Throwable throwable = e.getTargetException();
			Logger.error(throwable);
			throw new UtilsException(throwable.getMessage());
		} catch(Exception e) {
			Logger.error(e);
			throw new UtilsException("转换失败");
		}
	}
}
